package com.fanfanwang.ffw.app.db;

import java.util.Set;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.fanfanwang.ffw.app.db.ItotemContract.Tables;
import com.fanfanwang.ffw.app.db.ItotemContract.Tables.AbstractTable;
import com.fanfanwang.ffw.app.db.ItotemContract.Tables.UserBeanTable;

public class ItotemDB {
	private static final String TAG = ItotemDB.class.getSimpleName();

	private static final String DATABASE_NAME = "ffw.db";

	private static SQLiteDatabase mSQLiteDB;

	private static ItotemDBOpenHelper mDBOpenHelper;

	private static Context mContext;

	public ItotemDB(Context context) {
		mContext = context;
	}

	public ItotemDB open() {
		mDBOpenHelper = new ItotemDBOpenHelper(mContext, DATABASE_NAME, null, ItotemContract.DB_VERSION);
		mSQLiteDB = mDBOpenHelper.getWritableDatabase();
		return this;
	}

	/**
	 * 获取数据库 应用内的数据库操作都是从此获取数据库后直接CRUD操作
	 * 
	 * @param context
	 * @return
	 */
	public static SQLiteDatabase getDatabase(Context context) {

		if (mSQLiteDB != null && mSQLiteDB.isOpen()) {
			return mSQLiteDB;
		}

		mDBOpenHelper = new ItotemDBOpenHelper(mContext, DATABASE_NAME, null, ItotemContract.DB_VERSION);
		mSQLiteDB = mDBOpenHelper.getWritableDatabase();
		return mSQLiteDB;
	}

	public void close() {
		mDBOpenHelper.close();
	}

	public void beginTransaction() {
		mSQLiteDB.beginTransaction();
	}

	public void endTransaction() {
		if (mSQLiteDB.inTransaction()) {
			mSQLiteDB.endTransaction();
		}
	}

	public void setTransactionSuccessful() {
		mSQLiteDB.setTransactionSuccessful();
	}

	private static final class ItotemDBOpenHelper extends SQLiteOpenHelper {

		public ItotemDBOpenHelper(Context context, String name, CursorFactory factory, int version) {
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			final Set<Class<? extends AbstractTable>> tables = Tables.getTables();
			for (Class<? extends AbstractTable> table : tables) {
				try {
					for (String statment : Tables.getCreateStatments(table)) {
						Log.d(TAG, statment);
						db.execSQL(statment);
					}
				} catch (Throwable e) {
					Log.e(TAG, "Can't create table " + table.getSimpleName());
				}
			}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.d(TAG, "onUpgrade: " + oldVersion + " >> " + newVersion);
			final Set<Class<? extends AbstractTable>> tables = Tables.getTables();
			for (Class<? extends AbstractTable> table : tables) {
				try {
					db.execSQL("DROP TABLE IF EXISTS " + Tables.getTableName(table));
				} catch (Throwable e) {
					Log.e(TAG, "Can't create table " + table.getSimpleName());
				}
			}
			onCreate(db);
		}

	}

	public void cleanTable(String tableName, int maxSize, int batchSize) {
		Cursor cursor = mSQLiteDB.rawQuery("select count(_id) from " + tableName, null);
		if (cursor.getCount() != 0 && cursor.moveToFirst() && !cursor.isAfterLast()) {
			if (cursor.getInt(0) >= maxSize) {
				int deleteSize = maxSize - batchSize;
				mSQLiteDB.execSQL("delete from " + tableName + " where _id in (" + "select _id from " + tableName + " order by _id " + "  limit " + deleteSize
						+ " )");
			}
		}
		cursor.close();
	}

	// ---------------------user----------------------------------
	public long addUser(ContentValues values) {
		long aff = 0;
		if (values.containsKey(UserBeanTable.USER_ID)) {
			
			aff = updateUser(values, UserBeanTable.USER_ID + "=? and "+UserBeanTable.USER_NAME+"=?", new String[] { values.getAsString(UserBeanTable.USER_ID),values.getAsString(UserBeanTable.USER_NAME) });
			if (aff == 0) {
				aff = mSQLiteDB.insert(UserBeanTable.TABLE_NAME, "", values);
			}
		}
		return aff;

	}

	public int updateUser(ContentValues values, String whereClause, String[] whereArgs) {
		return mSQLiteDB.update(UserBeanTable.TABLE_NAME, values, whereClause, whereArgs);
	}

	public int deleteAllUser(){
		return mSQLiteDB.delete(UserBeanTable.TABLE_NAME, null, null);
	}
	
	public int deleteUserByUserid(String user_id) {
		return mSQLiteDB.delete(UserBeanTable.TABLE_NAME, UserBeanTable.USER_ID + "=?", new String[] { user_id });
		}

	public Cursor getUserById(String user_id) {
		return mSQLiteDB.query(Tables.UserBeanTable.TABLE_NAME, null, UserBeanTable.USER_ID + "=?", new String[] { user_id }, null, null, null);
	}
	
	public Cursor getUser() {
		return mSQLiteDB.rawQuery("select * from user_table", null);
	}
}
